package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        //jdbc操作
        List<User> users=new ArrayList<>();
       Connection connection=null;
       PreparedStatement preparedStatement =null;
       ResultSet resultSet =null;

        //jdbc 查询
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
                connection = DriverManager.getConnection(url, "root", "111111");
                // if(connection !=null){
                //    System.out.println("连接成功");
                //  }
                String sql = "select * from user";

                preparedStatement = connection.prepareStatement(sql);

                resultSet = preparedStatement.executeQuery();


                while (resultSet.next()) {

                    User user = new User();
                    user.setId(resultSet.getInt(1));
                    user.setName(resultSet.getString(2));
                    user.setPass(resultSet.getString(3));
                    //把对象添加到集合中
                    users.add(user);
                }
                return users;
            }catch (SQLException e){
                throw new RuntimeException(e);

            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }finally{
                try {
                    if(resultSet!=null){
                        resultSet.close();
                    }
                    if(preparedStatement!=null){
                        resultSet.close();
                    }
                    if(connection!=null){
                        resultSet.close();
                    }
                }catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

           // return null;
    }
}
